package cn.edu.ctbu.datajpa01.webapi;


import cn.edu.ctbu.datajpa01.core.PageUtils;
import cn.edu.ctbu.datajpa01.core.RUtil;
import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.service.StudentService;
import cn.edu.ctbu.datajpa01.vo.R;
import jdk.nashorn.internal.runtime.regexp.joni.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;


@RestController
@Slf4j
@RequestMapping("/webapi/student")
public class StudentRestController {
    @Autowired
    private StudentService studentService;

    /**
     * 读取的url:/webapi/student/list
     * @return
     */
    @GetMapping("/list")
    public List<Student> getAll(){
        List<Student> students = studentService.findAll();

        return students;
    }

    /**
     * 分页读取全部内容
     * @return
     */
//    @GetMapping("/getbypage")
//    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
//                               @RequestParam(value = "size",defaultValue = "10") Integer size){
//
//        //按id排倒序
//        Sort sort = Sort.by(Sort.Direction.DESC,"id");
//        Pageable pageable = PageRequest.of(page, size, sort);
//        Page<Student> studentPage = studentService.findAll(pageable);
//
//
//        PageUtils pageUtils = new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
//        return pageUtils;
//    }
    @GetMapping("/getbypage")
    public R<PageUtils> getByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
                                 @RequestParam(value = "size",defaultValue = "10") Integer size,
                                 @RequestParam(value = "name",defaultValue = "") String name){

        //按id排倒序
        Sort sort = Sort.by(Sort.Direction.DESC,"id");

        Page<Student> studentPage;

        if (StringUtils.isEmpty(name)){
            Pageable pageable = PageRequest.of(page,size,sort);
            studentPage = studentService.findAll(pageable);
        }else {
            Student student = new Student();
            student.setName(name);

            Pageable pageable = PageRequest.of(0,10,sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());

            Example<Student> example = Example.of(student,matcher);

            studentPage = studentService.findAll(example,pageable);
        }




        PageUtils pageUtils = new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return RUtil.success(pageUtils);
    }

    /**
     * 读取的url:/webapi/student/get/id
     * @return
     */
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){
        Student student = studentService.getById(id);



        return student;
    }

    /**
     *  查询学生方法:/webapi/student/find
     *
     * @return
     */
    @GetMapping("/find")
    public List<Student> findByName(@Valid String name){
        List<Student> students = studentService.findByName(name);
        return students;
    }


    /**  
     * 新增学生方法:/webapi/student/insert
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public R insert(@Valid Student student ,BindingResult bindingResult){

        if (bindingResult.hasErrors()){

            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生出错了！{}",errorMsg);
            return RUtil.error(-10,errorMsg);

        }

        studentService.insert(student);
//        return student.getId();
        return RUtil.success();
    }

    /**
     * 更新学生方法:/webapi/student/update
     * @param student
     * @return
     */
    @PutMapping("/update")
    public int update(@Valid Student student,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return -1;

        }

        Student oldstudent =studentService.getById(student.getId());
        if (StringUtils.isEmpty(student.getPassword())){
            student.setPassword(oldstudent.getPassword());
        }
        studentService.update(student);
        return student.getId();
    }

    /**
     * 删除学生方法:/webapi/student/delete
     * @param
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id){
        studentService.delete(id);

    }


    @GetMapping("/validateUser")
    public R validateSnoAndPassword(String num,String password) throws Exception{
      return  RUtil.success(studentService.validateUsernameAndPassword(num,password));

    }




}
